import { Injectable } from "@angular/core";
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers } from "@angular/http";
import { Observable } from "rxjs/Rx";

import { Router } from '@angular/router';

import { ToastyService, ToastyConfig, ToastOptions, ToastData } from '../modules/ng2-toasty';

@Injectable()
export class InterceptedHttp extends Http {

  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private router: Router, private toastyService: ToastyService) {

    super(backend, defaultOptions);

  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {

    return this.intercept(super.get(url, this.getRequestOptionArgs(options)));
  }

  post(url: string, body: any, options): Observable<Response> {

    //form data encodeURIComponent
    let str = [];
    for (let p in body) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(body[p]));
    }
    body = str.join("&");

    console.log(body);

    if (options == null) {
      options = new RequestOptions();
    }
    if (options.headers == null) {
      options.headers = new Headers();
    }
    options.headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return this.intercept(super.post(url, body, options));
  }

  put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {

    return super.put(url, body, this.getRequestOptionArgs(options));
  }

  delete(url: string, options?: RequestOptionsArgs): Observable<Response> {

    return super.delete(url, this.getRequestOptionArgs(options));
  }


  // 添加header
  private getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
    if (options == null) {
      options = new RequestOptions();
    }
    if (options.headers == null) {
      options.headers = new Headers();
    }
    options.headers.append('Content-Type', 'application/json')

    return options;
  }

  // reponse 拦截
  intercept(observable: Observable<Response>): Observable<Response> {



    return observable.map((res) => {

      // console.log(res);

      let data = res.json();

      // console.log("链接");
      // console.log(data);


      if (data.code === 0) {

        // console.log(0);

        return data;

      } else {

        // 用户过期
        if (data.msg === "Bad token") {
          // 销毁用户
          // this.authService.destroy();

          if (window.localStorage.getItem('channel') == '1') {
            window.location.href = "http://yunqi.shopex.cn/";
          } else {
            this.router.navigate(['/login']);
          }

        }

        let url = window.location.pathname;
        // console.log(window.location.pathname);
        if (url.charAt(url.length - 1) == "/" || url.match('/login') || url.match('/reg') || url.match('/forget')) {
          // 在根路径下不弹错误提示
        } else {

          if (data.msg === "Bad token") {
            // 用户过期不弹错误提示
          } else {
            // toast
            let toastOptions: ToastOptions = {
              title: "",
              msg: data.msg,
              showClose: true,
              timeout: 6000,
              theme: 'material'
            };
            // Add see all possible types in one shot
            this.toastyService.error(toastOptions);
          }


        }



        throw Observable.throw(data).error;

      }




    }).catch((err) => {

      console.log("Caught error: " + err);

      // toast
      /* let toastOptions: ToastOptions = {
         title: "",
         msg: '504',
         showClose: true,
         timeout: 6000,
         theme: 'material'
       };*/
      // Add see all possible types in one shot
      /*this.toastyService.error(toastOptions);*/

      throw Observable.throw(err);

    });



  }


}
